﻿<?php
	$constSalt = "moha";
	function strFilter($s){
		$s = str_replace(" ","a",$s);
		$s = str_replace("/","a",$s);
		$s = str_replace("\\","a",$s);

		return $s;
	}
	function randStr($len){
		if($len>1000 || $len <= 0){
			return NULL;
		}else{
			$s = "";
			for($i=0;$i<$len;++$i){
				$t = chr((rand(0,100)%26+ord('A')));
						
				$b = rand(0,2)%2;
				
				if($b == 0){
					$t = chr(ord($t) - ord('A') + ord('a'));
				}
				
				$s = $s.$t;
			}	
			return $s;
			
		}
	}
	
	
	
	function simpleVerify($s,$vers){
		if(strcmp(specialEncode($s,""),$vers) == 0)return true;
		else return false;
	}
	//已连接数据库
	function verifyUserAndDevice($hauser,$hadevice){
		//将空格,/过滤掉
		//$hauser = strFilter($hauser);
		//echo "$hauser";
		//1.先查询该用户是否存在
		$res = mysql_query('select `uid` from `user` where `hauser`="'.$hauser.'" limit 0,1') or die('error to select');
//		$res = mysql_query("select `uid` from `user` where `hauser`=".$hauser." limit 0,1")or die('error to select');
		if(!$res || empty($res))return null;
		$res = mysql_fetch_array($res);
		// if($res == NULL){
			// return null;
		// }
		//echo "res:$res";
		$uid = $res['uid'];
		//echo "uid:$uid";
		//2.再查询该设备是否为其所有
		//$hadevice = strFilter($hadevice);
		$res = mysql_query('select did from device where hadevice="'.$hadevice.'" and uid='.$uid.' limit 0,1');
		//$res = mysql_query("select `did` from `device` where `hadevice`=".$hadevice." and `uid`=".$uid." limit 0,1") ;
		if(!$res || empty($res))return null;
		$res = mysql_fetch_array($res);
		// if($res == NULL){
			// return null;
		// }
		$did = $res['did'];
		return array($uid,$did);
	}
	function specialEncode($m,$salt){
		$res = base64_encode($salt.$m.$salt);
		$res = base64_encode($res.$salt);
		$resmd5 = md5($res).$res;
		return $resmd5;
	}
	function specialDecode($E,$salt){
		$E = substr($E,32,strlen($E)-32);
		$res = base64_decode($E);
		$le = strlen($salt);
		$res = substr($res,0,strlen($res)-$le);
		$res = base64_decode($res);
		$res = substr($res,$le,strlen($res)-2*$le);
		return $res;
	}
	function calHauser($userId,$salt){
		global $constSalt;
		if($salt == null){
			$salt = $constSalt;
		}
		$res = specialEncode($userId,$salt);
		$res = substr($res,0,32);
		return $res;
	}
	//for test
//	echo calHauser(7,null);
	//echo randStr(20);
?>

